package cn.codesea.housework_user.ui;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.codesea.housework_user.R;
import cn.codesea.housework_user.entity.User;
import cn.codesea.housework_user.net.ServiceGenerator;
import cn.codesea.housework_user.net.data.Result;
import cn.codesea.housework_user.net.service.UserService;
import cn.codesea.housework_user.utils.SPUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterChildActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.pwd_et)
    EditText pwd_et;
    @BindView(R.id.name_et)
    EditText name_et;
    @BindView(R.id.sex_et)
    EditText sex_et;
    @BindView(R.id.cif_et)
    EditText cif_et;
    @BindView(R.id.phone_et)
    EditText phone_et;
    @BindView(R.id.birth_et)
    EditText birth_et;
    @BindView(R.id.address_et)
    EditText address_et;
    @BindView(R.id.company_et)
    EditText company_et;
    @BindView(R.id.career_et)
    EditText career_et;

    @BindView(R.id.submit_tv)
    AppCompatButton submit_tv;

    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_child);
        ButterKnife.bind(this);
        init();
    }

    private void init(){

        Intent data = getIntent();
        String type = data.getStringExtra("type");
        if("update".equals(type)){
            user = new Gson().fromJson(SPUtil.get(RegisterChildActivity.this,SPUtil.USER,""),User.class);
        }

        initView();
    }

    public void initToolbar(){
        // 初始化 toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterChildActivity.this,MainActivity.class));
            }
        });
    }

    public void initView(){

        initToolbar();

        if(user != null){
            pwd_et.setText(user.getPwd());
            name_et.setText(user.getName());
            sex_et.setText(user.getSex());
            cif_et.setText(user.getCif_no());
            phone_et.setText(user.getPhone());
            birth_et.setText(user.getBirth());
            address_et.setText(user.getAdress());
            company_et.setText(user.getCompany());
            career_et.setText(user.getCareer());
        }
    }

    @OnClick({R.id.sex_et})
    public void sex_et(){
        showDialog_sex(sex_et);
    }

    @OnClick({R.id.birth_et})
    public void birth_et(){
        showDialog_birth(birth_et);
    }

    @OnClick(R.id.submit_tv)
    public void submit_tv(){

        User user = new User();
        user.setType(0);// 子女注册
        user.setPwd(pwd_et.getText().toString());
        user.setName(name_et.getText().toString());
        user.setSex(sex_et.getText().toString());
        user.setCif_no(cif_et.getText().toString());
        user.setPhone(phone_et.getText().toString());
        user.setAdress(address_et.getText().toString());
        user.setBirth(birth_et.getText().toString());
        user.setCompany(company_et.getText().toString());
        user.setCareer(career_et.getText().toString());

        // 网络请求
        UserService service = ServiceGenerator.createService(UserService.class);

        if (this.user == null){// 注册流程
            Call<Result> call = service.userRegister(user);
            call.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    resultProcess(response.body(),"注册");
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(RegisterChildActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });
        }else {// 修改流程

            user.setUserid(this.user.getUserid());

            Call<Result> call = service.userUpdate(user);
            call.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    resultProcess(response.body(),"修改");
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(RegisterChildActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });
        }


    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result,String msg){
        if (result.getState() == 200){
            Dialog dialog = new AlertDialog.Builder(RegisterChildActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "成功！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            startActivity(new Intent(RegisterChildActivity.this,LoginActivity.class));
                            finish();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }else {
            Dialog dialog = new AlertDialog.Builder(RegisterChildActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "失败！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    /**
     * 性别选择
     * @param et
     */
    public void showDialog_sex(final EditText et){
        final String[] Items = new String[] {"男","女"};
        Dialog allertDialog = new AlertDialog.Builder(RegisterChildActivity.this).setItems(Items,new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                et.setText(Items[which]);
            }
        } ).create();
        allertDialog.show();
    }

    /**
     * 日期选择
     * @param et
     */
    public void showDialog_birth(final EditText et){
        new DatePickerDialog(RegisterChildActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        monthOfYear += 1;
                        et.setText(year+"-"+monthOfYear+"-"+dayOfMonth);
                    }
                }, Calendar.getInstance().get(Calendar.YEAR), Calendar
                .getInstance().get(Calendar.MONTH), Calendar
                .getInstance().get(Calendar.DATE)).show();
    }


}
